﻿using System;
using System.Collections.Generic;
using System.Text;
using DialectSoftware.Networking;
using System.Linq;

namespace WebFabricator.org.Management
{
    public class SLSMPResponse
    {
        private SLSMPResponse()
        { 
        
        }

        public SLSMPResponse(SLSMPRequest request, SLSMP method, string data)
        {
            Method = method;
            RequestMethod = request.Method;
            TransactionID = request.TransactionID;
            Data = data;
        }

        public Guid TransactionID
        {
            get;
            private set;
        }

        public SLSMP Method
        {
            get;
            private set;
        }

        public SLSMP RequestMethod
        {
            get;
            private set;
        }

        public String Data
        {
            get;
            private set;
        }

        public byte[] ToByteArray()
        {
            return System.Text.ASCIIEncoding.UTF8.GetBytes(String.Join("|", new[] { TransactionID.ToString(), Method.ToString(), RequestMethod.ToString(), Data??String.Empty }) + "^");
        }

        public static IEnumerable<SLSMPResponse> Parse(AsyncNetworkAdapter adapter)
        {
            string data = System.Text.ASCIIEncoding.UTF8.GetString(adapter.Buffer);
            var requests = data.Split('^');
            return requests
                .Where(r => !String.IsNullOrEmpty(r))
                .Select(r => {
                        int i = 0;
                        SLSMPResponse response = new SLSMPResponse();
                        r.Split('|').ForEach(s =>
                        {
                            switch (i)
                            {
                                case 0:
                                    response.TransactionID = new Guid(s);
                                    break;
                                case 1:
                                    response.Method = (SLSMP)Enum.Parse(typeof(SLSMP), s);
                                    break;
                                case 2:
                                    response.RequestMethod = (SLSMP)Enum.Parse(typeof(SLSMP), s);
                                    break;
                                case 3:
                                    response.Data = s;
                                    break;
                                default:
                                    throw new NotSupportedException(data);
                            }
                            i++;
                        });
                return response;
            });
            
        }
    }
}
